/*
 * Copyright (C) 2020 ~ 2021 Deepin Technology Co., Ltd.
 *
 * Author:     zhangbingyi <zhangbingyi@uniontech.com>
 *
 * Maintainer: zhangbingyi <zhangbingyi@uniontech.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "multiselectlistview.h"

#include <QKeyEvent>
#include <QMouseEvent>
#include <QDebug>

MultiSelectListView::MultiSelectListView(QWidget *parent)
    : QListView(parent)
{
}

// 重置状态
void MultiSelectListView::resetStatus(const QModelIndex &index)
{
    m_currentIndex = index.row();
    QListView::clearSelection();
    QListView::setSelectionMode(QListView::SingleSelection);
    QListView::setCurrentIndex(index);
}

// 当前刚选中改变
void MultiSelectListView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    QListView::setSelectionMode(QListView::SingleSelection);
    QListView::currentChanged(current, previous);
}

// 光标移动
QModelIndex MultiSelectListView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
{
    QListView::setSelectionMode(QListView::MultiSelection);
    return QListView::moveCursor(cursorAction, modifiers);
}

// 键盘事件
void MultiSelectListView::keyPressEvent(QKeyEvent *event)
{
    // 获取向上方向键点击事件
    if (event->key() == Qt::Key_Up) {
        QModelIndex nextIndex = model()->index(m_currentIndex - 1, 0);
        if (nextIndex.isValid()) {
            if (isRowHidden(m_currentIndex - 1)) {
                if (m_currentIndex - 1 <= 0) {
                    return;
                }
                m_currentIndex--;
                keyPressEvent(event);
                return;
            }
            setCurrentIndex(nextIndex);
            Q_EMIT pressed(nextIndex);
        }
        return;
    } else if (event->key() == Qt::Key_Down) {
        // 获取向下方向键点击事件
        QModelIndex nextIndex = model()->index(m_currentIndex + 1, 0);
        if (nextIndex.isValid()) {
            if (isRowHidden(m_currentIndex + 1)) {
                if (model()->rowCount() - 1 <= m_currentIndex + 1) {
                    return;
                }
                m_currentIndex++;
                keyPressEvent(event);
                return;
            }
            setCurrentIndex(nextIndex);
            Q_EMIT pressed(nextIndex);
        }
        return;
    }
    return QListView::keyPressEvent(event);
}
